<template>
  <div v-loading="getDetailLoading" class="code_detail">
    <div class="header">
      <div class="status">
        <div class="title"> 序列号：{{ detail.securityCode }}</div>
        <HStatus v-if="detail.type === 1">成品</HStatus>
        <HStatus v-else-if="detail.type === 2" type="warning">物料</HStatus>
        <HStatus v-if="detail.activa" type="success">已激活</HStatus>
        <HStatus v-else type="info">未激活</HStatus>
        <HStatus v-if="detail.status === 1" type="info">未质保</HStatus>
        <HStatus v-if="detail.status === 2">质保中</HStatus>
        <HStatus v-if="detail.status === 3" type="warning">已过保</HStatus>
        <HStatus v-if="detail.status === 4" type="error">已作废</HStatus>
      </div>
      <div class="btn_group">
        <HPlainButton v-if="userStore.isCurrentRoleNetwork" @click="onApplyUpdateWarrantyRange">
          申请变更质保周期
        </HPlainButton>
        <HPlainButton v-else @click="updateWarrantyRangeModalVisible = true">
          变更质保周期
        </HPlainButton>
        <HPlainButton
          v-if="detail.status != 1"
          v-permission="'code_changeRegister'"
          @click="changeuserRegister"
        >
          变更登记地址
        </HPlainButton>
        <HPlainButton
          v-if="detail.register"
          v-permission="'code_changeCustomer'"
          @click="onUpdateUserClick"
        >
          {{ userStore.isCurrentRoleNetwork ? '申请变更公司' : '变更公司' }}
        </HPlainButton>
        <HPlainButton v-permission="'order_add'" @click="onCreateOrderClick">新建工单</HPlainButton>
        <!-- <HPlainButton v-if="!detail.register" @click="changeEditField"
					>修改导入字段</HPlainButton
				> -->
        <HPlainButton v-permission="'code_edit'" @click="changeInf">修改序列号物料</HPlainButton>
        <HPlainButton v-if="!detail.activa" v-permission="'code_active'" @click="activeOpen">
          手动激活
        </HPlainButton>
        <HPlainButton
          v-if="detail.status == 1"
          v-permission="'code_userRegister'"
          @click="userRegister"
        >
          登记公司
        </HPlainButton>
        <HPlainButton v-if="!detail.activa" v-permission="'code_del'" type="error" @click="deleCo">
          删除序列号
        </HPlainButton>
      </div>
    </div>

    <div class="body">
      <!-- 基本信息 -->
      <div class="basic_info">
        <template v-if="detail">
          <div class="title">基本信息</div>
          <div class="info_list">
            <div class="info_item_container">
              <div class="info_item">
                <div class="label">物料类型:</div>
                <HStatus v-if="detail.type === 1">成品</HStatus>
                <HStatus v-else-if="detail.type === 2" type="warning">物料</HStatus>
              </div>
              <!-- <div class="info_item">
								<div class="label">物料品牌:</div>
								<div class="value">{{ detail.brand }}</div>
							</div> -->
              <div class="info_item">
                <div class="label">序列号来源:</div>
                <div class="value">
                  <span v-if="detail.codeSource === 1">系统创建</span>
                  <span v-if="detail.codeSource === 2">系统导入</span>
                  <span v-if="detail.codeSource === 3">工单报单创建</span>
                  <span v-if="detail.codeSource === 5">金蝶云星空</span>
                </div>
              </div>
              <div class="info_item">
                <div class="label">创建时间:</div>
                <div class="value">{{ detail.createTime }}</div>
              </div>
            </div>
            <div class="info_item_container">
              <div class="info_item">
                <div class="label">物料名称:</div>
                <!-- <div class="value">{{ detail.goodsName }}</div> -->
                <ShowTooltip
                  :content="detail.goodsName || ''"
                  :is-text="true"
                  :offset="5"
                  :show-after="200"
                  :size="12"
                  class-name="is_textClass"
                  color="#000"
                  placement="top"
                  ref-name="testName2"
                ></ShowTooltip>
              </div>
              <div class="info_item">
                <div class="label">物料编号:</div>
                <div class="value">{{ detail.goodsCode }}</div>
              </div>
              <div class="info_item">
                <div class="label">最后更新:</div>
                <div class="value">{{ detail.updateTime }}</div>
              </div>
            </div>
            <div class="info_item_container">
              <div class="info_item">
                <div class="label">物料型号:</div>
                <!-- <div class="value">{{ detail.model }}</div> -->
                <ShowTooltip
                  :content="detail.model || ''"
                  :is-text="true"
                  :offset="5"
                  :show-after="200"
                  :size="12"
                  class-name="is_textClass"
                  color="#000"
                  placement="top"
                  ref-name="testName2"
                ></ShowTooltip>
              </div>
              <div class="info_item">
                <div class="label">物料规格:</div>
                <!-- <div class="value">{{ detail.goodsSpecName }}</div> -->
                <ShowTooltip
                  :content="detail.goodsSpecName || ''"
                  :is-text="true"
                  :offset="5"
                  :show-after="200"
                  :size="12"
                  class-name="is_textClass"
                  color="#000"
                  placement="top"
                  ref-name="testName2"
                ></ShowTooltip>
              </div>
              <div class="info_item">
                <div class="label">合同号:</div>
                <!-- <div class="value">{{ detail.goodsSpecName }}</div> -->
                <ShowTooltip
                  :content="detail.contractNo || ''"
                  :is-text="true"
                  :offset="5"
                  :show-after="200"
                  :size="12"
                  class-name="is_textClass"
                  color="#000"
                  placement="top"
                  ref-name="testName2"
                ></ShowTooltip>
              </div>
            </div>
            <div class="info_item_container">
              <div class="info_item">
                <div class="label" style="width: 75px">登记公司信息:</div>
                <ShowTooltip
                  :content="`${detail.username || ''} ${detail.phone || ''}`"
                  :is-text="true"
                  :offset="5"
                  :show-after="200"
                  :size="12"
                  class-name="is_textClass"
                  color="#000"
                  placement="top"
                  ref-name="testName2"
                ></ShowTooltip>
              </div>
              <div class="info_item">
                <div class="label" style="width: 75px">登记地址:</div>
                <div class="value">
                  <ShowTooltip
                    :content="
                      detail.province + detail.city + detail.area + detail.town + detail.address ||
                      ''
                    "
                    :is-text="true"
                    :offset="5"
                    :show-after="200"
                    :size="12"
                    class-name="is_textClass"
                    color="#000"
                    placement="top"
                    ref-name="testName"
                  ></ShowTooltip>
                </div>
              </div>
            </div>
            <!-- <div class="info_item_container"> -->

            <!-- <div class="info_item">
								<div class="label">生产日期:</div>
								<div class="value">{{ detail.produceDate }}</div>
							</div> -->
            <!-- </div> -->
            <!-- <div class="info_item_container"> -->
            <!-- <div class="info_item">
								<div class="label">销售部门编号:</div>
								<ShowTooltip
									placement="top"
									ref-name="testName2"
									class-name="is_textClass"
									:content="detail.saleNetworkNumber || ''"
									:is-text="true"
									color="#000"
									:size="12"
									:offset="5"
									:show-after="200"
								></ShowTooltip>
							</div> -->
            <!-- <div class="info_item">
								<div class="label">销售部门:</div>
								<ShowTooltip
									placement="top"
									ref-name="testName2"
									class-name="is_textClass"
									:content="detail.saleNetworkName || ''"
									:is-text="true"
									color="#000"
									:size="12"
									:offset="5"
									:show-after="200"
								></ShowTooltip>
							</div> -->
            <!-- <div class="info_item">
								<div class="label">销售金额:</div>
								<div class="value">￥{{ Number(detail.salePrice || 0).toFixed(2) }}</div>
								<ShowTooltip
									placement="top"
									ref-name="testName2"
									class-name="is_textClass"
									:content="`￥${Number(detail.salePrice || 0).toFixed(2)}`"
									:is-text="true"
									color="#000"
									:size="12"
									:offset="5"
									:show-after="200"
								></ShowTooltip>
							</div> -->
            <!-- </div> -->
          </div>
        </template>
      </div>
      <div class="table_code_info">
        <div class="coded_message">
          <div class="title">
            <div class="text">质保信息</div>
          </div>
          <div class="line"></div>
          <el-form class="form_list" label-width="74px">
            <el-form-item class="security_code" label="序列号">
              <span
                class="security_code_content"
                style="display: flex; align-items: center; height: 100%"
                >{{ detail.securityCode }}</span
              >
            </el-form-item>
            <!-- <el-form-item label="批次编号">
							<span>{{ detail.batchCode }}</span>
						</el-form-item> -->

            <!-- <el-form-item label="激活时间">
              <span>{{ detail.activaTime }}</span>
            </el-form-item>
            <el-form-item label="激活状态">
              <HStatus v-if="detail.activa" type="success">
                <span style="font-size: 12px">已激活</span>
              </HStatus>
              <HStatus v-else type="info">
                <span style="font-size: 12px">未激活</span>
              </HStatus>
            </el-form-item>
            <el-form-item label="登记时间">
              <span>{{ detail.registerTime }}</span>
            </el-form-item> -->
            <el-form-item label="设备属性">
              <div style="display: flex; align-items: baseline; column-gap: 6px">
                {{ detail.standby === 1 ? '备用机' : '' }}
                <h-link
                  style="height: 12px; display: flex; align-items: center"
                  @click="setBackupMachineModalVisible = true"
                >
                  <el-icon>
                    <Edit />
                  </el-icon>
                </h-link>
              </div>
            </el-form-item>
            <el-form-item label="序列号状态">
              <HStatus v-if="detail.status === 1" type="info">
                <span style="font-size: 12px">未质保</span>
              </HStatus>
              <HStatus v-else-if="detail.status == 2">
                <span style="font-size: 12px">质保中</span>
              </HStatus>
              <HStatus v-else-if="detail.status == 3" type="info">
                <span style="font-size: 12px">已过保</span>
              </HStatus>
              <HStatus v-else type="error">
                <span style="font-size: 12px">已作废</span>
              </HStatus>
            </el-form-item>
            <el-form-item label="质保开始">
              <div class="flex align-center column-gap-5px">
                <span>{{ detail.warrantyStartTime }}</span>
                <!--<div style="cursor: pointer; display: flex; align-items: center">-->
                <!--  <el-icon-->
                <!--    v-permission="'code_updateWarranty'"-->
                <!--    color="#007cff"-->
                <!--    size="16"-->
                <!--    @click="updateWarrantyModalVisible = true"-->
                <!--  >-->
                <!--    <Edit />-->
                <!--  </el-icon>-->
                <!--</div>-->
              </div>
            </el-form-item>
            <el-form-item label="质保截止">
              <span>{{ detail.warrantyEndTime }}</span>
            </el-form-item>
            <el-form-item label="质保周期">
              <span>{{ detail.warrantyDay || 0 }}天</span>
            </el-form-item>
            <!-- <el-form-item label="首次查询">
              <span>{{ detail.firstSelectTime }}</span>
            </el-form-item>
            <el-form-item label="最后查询">
              <span>{{ detail.lastSelectTime }}</span>
            </el-form-item>
            <el-form-item label="查询次数">
              <span>{{ detail.selectNum }}</span>
            </el-form-item> -->
            <p class="bor_link"></p>

            <!-- <el-form-item label="出库仓编号">
							<ShowTooltip
								placement="top"
								ref-name="testName1"
								class-name="is_className"
								:content="detail.outboundStoreNumber || ''"
								:is-text="true"
								color="#000"
								:size="12"
								:offset="5"
								:show-after="200"
							></ShowTooltip>
						</el-form-item> -->
            <el-form-item label="出库状态">
              <HStatus v-if="detail.storeStatus === 1" type="info">未出入库</HStatus>
              <HStatus v-if="detail.storeStatus === 2" type="warning">预入库</HStatus>
              <HStatus v-if="detail.storeStatus === 3" type="success">已入库</HStatus>
              <HStatus v-if="detail.storeStatus === 4" type="warning">预出库</HStatus>
              <HStatus v-if="detail.storeStatus === 5" type="success">已出库</HStatus>
            </el-form-item>
            <!-- <el-form-item label="出库时间">
              {{ detail.outboundTime }}
            </el-form-item> -->
            <!-- <el-form-item label="销货单号">
							<ShowTooltip
								placement="top"
								ref-name="testName1"
								class-name="is_className"
								:content="detail.outboundCode || ''"
								:is-text="true"
								color="#000"
								:size="12"
								:offset="5"
								:show-after="200"
							></ShowTooltip>
						</el-form-item> -->
            <!-- <el-form-item label="发货单号">
							<ShowTooltip
								placement="top"
								ref-name="testName1"
								class-name="is_className"
								:content="detail.sendGoodsNumber || ''"
								:is-text="true"
								color="#000"
								:size="12"
								:offset="5"
								:show-after="200"
							></ShowTooltip>
						</el-form-item> -->
            <!-- <el-form-item label="出厂日期">
							<span>{{ detail.dateOfProduction }}</span>
						</el-form-item> -->
            <!-- <el-form-item label="备注">
							<ShowTooltip
								placement="top"
								:ref-name="'testName1'"
								class-name="is_className"
								:content="detail.remark"
								:is-text="true"
								color="#666"
								:size="12"
								:offset="5"
								:show-after="300"
							></ShowTooltip>
						</el-form-item> -->
            <!-- <el-form-item label="入库单号">
							<span>{{ detail.inboundCode }}</span>
						</el-form-item>
						<el-form-item label="入库时间">
							<span>{{ detail.inboundTime }}</span>
						</el-form-item> -->
          </el-form>
        </div>
        <div class="tabs_container">
          <div class="tabs_header">
            <div class="tabs_options">
              <el-tabs
                v-model="activeName"
                v-loading="loadingtabs"
                element-loading-text="加载中..."
                @tab-change="activeNameChange"
              >
                <!-- 历史工单 -->
                <el-tab-pane label="历史工单" name="first" />

                <!-- 变更公司记录 -->
                <el-tab-pane label="变更公司记录" name="second" />

                <!-- 产品溯源 -->
                <el-tab-pane label="变更物料记录" name="third" />

                <!-- 变更质保记录 -->
                <el-tab-pane label="变更质保记录" name="updateWarrantyDateRangeLog" />

                <!-- 装配清单 -->
                <!-- <el-tab-pane label="装配清单" name="fifth" /> -->

                <!-- 工图 -->
                <el-tab-pane label="工图" name="workDrawings" />

                <!-- 操作日志 -->
                <el-tab-pane label="操作日志" name="fourth" />
              </el-tabs>
            </div>

            <header v-if="activeName === 'fourth'" class="operated_log_search">
              <el-input
                v-model.trim="getOperatedLogsParam.name"
                clearable
                placeholder="操作名字"
                @clear="getOperatedLogs"
                @keyup.enter="getOperatedLogs"
              />
              <el-input
                v-model.trim="getOperatedLogsParam.createEmp"
                clearable
                placeholder="操作人"
                @clear="getOperatedLogs"
                @keyup.enter="getOperatedLogs"
              />
              <HButton type="primary" @click="getOperatedLogs">
                <el-icon>
                  <Search />
                </el-icon>
                搜索
              </HButton>
            </header>
          </div>

          <div class="tabs_content">
            <!-- 历史工单 -->
            <div v-show="activeName === 'first'" class="history_order">
              <el-table :border="true" :data="historyOrder" height="100%" resizable stripe>
                <el-table-column
                  :align="'center'"
                  fixed="left"
                  label="序号"
                  type="index"
                  width="50"
                />
                <el-table-column
                  label="工单编号"
                  prop="orderNo"
                  show-overflow-tooltip
                  width="150px"
                >
                  <template #default="item">
                    <span
                      class="xy_main_btn"
                      @click="router.push('/order/odetail/' + item.row.id)"
                      >{{ item.row.orderNo }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  :align="'center'"
                  fixed="right"
                  label="工单状态"
                  prop="status"
                  width="100px"
                >
                  <template #default="scope">
                    <div class="flex_justify_center">
                      <HStatus v-if="scope.row.status === 1" type="warning">待派单</HStatus>
                      <HStatus v-if="scope.row.status === 2" type="warning">待部门确认</HStatus>
                      <HStatus v-if="scope.row.status === 3" type="warning">处理中</HStatus>
                      <HStatus v-if="scope.row.status === 4" type="success">已完成</HStatus>
                      <HStatus v-if="scope.row.status === 5" type="info">已取消</HStatus>
                    </div>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="等级" prop="workLevel" width="90px">
                  <template #default="item">
                    <span :style="{ color: item.row.workLevelColor }">{{
                      item.row.workLevel
                    }}</span>
                  </template>
                </el-table-column> -->
                <el-table-column prop="dateTime" label="报单时间" width="128" />
                <el-table-column label="工单费用" prop="totalPrice" width="90px">
                  <template #default="item">
                    <span>￥{{ (item.row.totalPrice || 0).toFixed(2) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="客户名称"
                  prop="username"
                  show-overflow-tooltip
                  width="130"
                />
                <el-table-column label="公司手机号" prop="phone" width="140" />
                <el-table-column label="部门" prop="network" show-overflow-tooltip width="130px" />
                <el-table-column label="最后更新" prop="updateTime" width="130px" />
              </el-table>
            </div>

            <!-- 更新公司记录 -->
            <div v-show="activeName === 'second'" class="update_customer_log">
              <div class="table">
                <el-table :border="true" :data="userchangeLOgData" height="100%" resizable stripe>
                  <template #empty>
                    <el-empty description="暂无数据" />
                  </template>
                  <el-table-column
                    fixed
                    label="变更次数"
                    prop="count"
                    show-overflow-tooltip
                    width="80"
                  >
                    <template #default="item">
                      <div class="change_alter">
                        <span>{{ item.row.count }}</span>
                        <img
                          alt="#"
                          class="img_zhankai"
                          src="../../../../assets/image/zhanpai.png"
                          @click="gochangeDetail(item.row)"
                        />
                      </div>
                    </template>
                  </el-table-column>

                  <!--物料名称-->
                  <!-- <el-table-column
                    label="物料名称"
                    prop="goodsName"
                    show-overflow-tooltip
                    width="290"
                  >
                    {{ detail.brand }} &nbsp; {{ detail.goodsName }} &nbsp;
                    {{ detail.model }} &nbsp;
                    {{ detail.goodsSpecName }}
                  </el-table-column> -->
                  <el-table-column
                    label="所属公司(新)"
                    prop="username"
                    show-overflow-tooltip
                    width="140"
                  />
                  <el-table-column
                    label="联系手机(新)"
                    prop="phone"
                    show-overflow-tooltip
                    width="140"
                  />
                  <el-table-column
                    label="地址(新)"
                    prop="address"
                    show-overflow-tooltip
                    width="140"
                  >
                    <template #default="item">
                      {{ item.row.province }} {{ item.row.city }} {{ item.row.area }}
                      {{ item.row.town }} {{ item.row.address }}
                    </template>
                  </el-table-column>
                  <el-table-column label="附件" prop="" show-overflow-tooltip width="140" />
                  <el-table-column
                    label="操作人"
                    prop="createEmp"
                    show-overflow-tooltip
                    width="140"
                  />

                  <!--审核备注-->
                  <el-table-column
                    label="审核备注"
                    prop="applyMsg"
                    width="120"
                    show-overflow-tooltip
                  />

                  <!--审核人员-->
                  <el-table-column label="审核人员" prop="applyName" width="120" />

                  <el-table-column
                    label="操作时间"
                    prop="createTime"
                    show-overflow-tooltip
                    width="140"
                  />

                  <el-table-column label="状态" fixed="right" :align="'center'" width="80">
                    <template #default="{ row }">
                      <div class="flex justify-center">
                        <h-status v-if="row.applyState === 0" type="warning">待审核</h-status>
                        <h-status v-if="row.applyState === 1">通过</h-status>
                        <h-status v-if="row.applyState === 2" type="error">驳回</h-status>
                      </div>
                    </template>
                  </el-table-column>

                  <!-- 操作 -->
                  <el-table-column
                    v-if="!userStore.isCurrentRoleNetwork"
                    fixed="right"
                    label="操作"
                    width="100"
                  >
                    <template #default="{ row }">
                      <h-space>
                        <h-link
                          :disabled="row.applyState !== 0"
                          @click="handleUpdateUserCheckClick(row.id)"
                          >审核</h-link
                        >
                        <!-- <h-link
                          type="error"
                          :disabled="row.applyState !== 0"
                          @click="handleUpdateUserRecordDelClick(row.id)"
                          >删除</h-link
                        > -->
                      </h-space>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="pagination">
                <Pagination
                  ref="paginDom"
                  :list_total="total"
                  @size-change="activeNameChange('second')"
                  @current-change="activeNameChange('second')"
                />
              </div>
            </div>

            <!-- 产品溯源 -->
            <div v-show="activeName === 'third'" class="product_resource">
              <div class="table">
                <el-table :border="true" :data="changeLOgData" height="100%" resizable stripe>
                  <template #empty>
                    <el-empty description="暂无数据" />
                  </template>
                  <el-table-column label="物料名称" prop="goodsName" show-overflow-tooltip>
                    <template #default="item">
                      {{ item.row.brand }} &nbsp; {{ item.row.goodsModel }} &nbsp;
                      {{ item.row.goodsName }} &nbsp;
                      {{ item.row.goodsSpecName }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作人"
                    prop="createEmp"
                    show-overflow-tooltip
                    width="140"
                  />
                  <el-table-column
                    label="操作时间"
                    prop="createTime"
                    show-overflow-tooltip
                    width="180"
                  />
                </el-table>
              </div>
              <div class="pagination">
                <Pagination
                  ref="paginDom"
                  :list_total="total"
                  @size-change="activeNameChange('second')"
                  @current-change="activeNameChange('second')"
                />
              </div>
            </div>

            <!-- 操作日志 -->
            <div v-show="activeName === 'fourth'" class="operated_log">
              <div class="table_container">
                <el-table :border="true" :data="operatedLogs" max-height="400">
                  <el-table-column label="事件" prop="name" show-overflow-tooltip />
                  <el-table-column label="操作内容" prop="content" show-overflow-tooltip />
                  <el-table-column label="操作人" prop="createEmp" show-overflow-tooltip />
                  <el-table-column label="操作时间" prop="createTime" show-overflow-tooltip />
                </el-table>
              </div>

              <div class="footer">
                <Pagination
                  ref="operatedLogPaginationRef"
                  :list_total="total"
                  @size-change="getOperatedLogs"
                  @current-change="getOperatedLogs"
                />
              </div>
            </div>

            <div v-if="activeName === 'workDrawings'" class="work-drawing">
              <WorkDrawingList
                :code-detail="detail"
                @update="getDetail(route.params.id as string)"
              />
            </div>

            <!--变更质保周期日志列表-->
            <update-warranty-date-range-apply-log-list
              v-if="activeName === 'updateWarrantyDateRangeLog'"
              ref="updateWarrantyDateRangeApplyLogListInstance"
              :code-id="detail.id"
              @update="getDetail(route.params.id as string)"
            />

            <!-- 装配清单 -->
            <mount-table
              v-if="activeName === 'fifth'"
              :code="detail.securityCode"
              @success="successMountList"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 变更公司弹窗 -->
    <UpdateUserModal
      v-model="updateUserModalVisible"
      :codedetail="detail"
      @update="onChangeCustomerUpdate"
    />

    <!-- 修改序列号信息弹窗 -->
    <h-dialog v-model="changeDialog" :loading="updateInfoSaveLoading" title="修改序列号信息">
      <el-form
        ref="updateInfoFormRef"
        :model="dataInfForm"
        :rules="updateInfoFormRules"
        class="modal_form_content"
        inline-message
        label-position="top"
      >
        <el-form-item label="当前信息">
          <el-input
            :value="
              detail.brand +
              '  ' +
              detail.goodsName +
              '  ' +
              detail.model +
              '  ' +
              detail.goodsSpecName
            "
            disabled
          />
        </el-form-item>
        <el-form-item class="same_line" label="序列号类型">
          <el-radio-group v-model="dataInfForm.type" @change="changeSwitch('')">
            <el-radio :value="1" size="small">成品</el-radio>
            <el-radio :value="2" size="small">物料</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="新的型号" prop="goodsId">
          <el-select
            v-model="dataInfForm.goodsId"
            :filter-method="remoteMethod2"
            :loading="loading3"
            class="w350"
            clearable
            filterable
            placeholder="请选择"
            remote-show-suffix
            @change="seleSwitch('')"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :disabled="item.model == detail.model"
              :label="item.model"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规格信息" prop="goodsSpecId">
          <el-select
            v-model="dataInfForm.goodsSpecId"
            :filter-method="remoteMethod3"
            :loading="loading4"
            clearable
            filterable
            placeholder="请选择"
            remote-show-suffix
          >
            <el-option
              v-for="item in options2"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <HButton is-modal type="primary" @click="onSvaeInf">保存</HButton>
        <HButton is-modal @click="changeDialog = false">取消</HButton>
      </template>
    </h-dialog>

    <!-- 登记用户弹窗 -->
    <h-dialog v-model="checkDialog" :loading="registerCustomerLoading" title="登记公司">
      <el-form
        ref="customerRegisterFormRef"
        :model="userForm"
        :rules="customerRegisterFormRules"
        class="modal_form_content"
        inline-message
        label-position="top"
      >
        <!-- 关联用户 -->
        <el-form-item label="关联公司" prop="userId">
          <el-select
            v-model="value4"
            :filter-method="remoteMethod"
            :loading="loading2"
            clearable
            filterable
            placeholder="请选择关联公司"
            remote-show-suffix
            @change="changeSel"
          >
            <el-option
              v-for="item in relevanceUser"
              :key="item.id"
              :label="item.name + ' ' + item.phone"
              :value="item.id"
              @click="getinformation(item)"
            />
          </el-select>
        </el-form-item>

        <!-- 登记姓名 -->
        <el-form-item label="登记姓名" prop="name">
          <el-input v-model.trim="userForm.name" clearable placeholder="请输姓名" />
        </el-form-item>

        <!-- 登记号码 -->
        <el-form-item label="登记号码" prop="phone">
          <el-input v-model.trim="userForm.phone" clearable placeholder="请输登记号码" />
        </el-form-item>

        <!-- 用户地址，prop="province"是因为，传递字符串在form里的值是一个对象的话不管有没有填值，required校验都过不了 -->
        <el-form-item label="公司地址" prop="province">
          <SingleAddress ref="addrsDom" :address="userForm.adds" @change="handleAddressChange" />
        </el-form-item>

        <!-- 详细地址 -->
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model.trim="userForm.address"
            clearable
            maxlength="200"
            placeholder="请输入详细地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <HButton is-modal type="primary" @click="onsaveCodeRegister">保存</HButton>
        <HButton is-modal @click="checkDialog = false">取消</HButton>
      </template>
    </h-dialog>

    <!-- 变更登记地址 -->
    <h-dialog
      v-model="checkDialogAddress"
      :loading="updateRegisterAddressSaveLoading"
      title="变更登记地址"
    >
      <el-form
        ref="updateRegisterAddressFormRef"
        :model="userchangeForm"
        :rules="updateRegisterAddressFormRules"
        class="modal_form_content"
        inline-message
        label-position="top"
      >
        <el-form-item class="same_line text" label="原地址:">
          {{ detail.province }} /{{ detail.city }}/{{ detail.area }}/{{ detail.address }}
        </el-form-item>
        <el-form-item label="新地址" prop="province">
          <SingleAddress
            ref="addrsDom2"
            :address="userchangeForm.adds"
            @change="handleChangeUserFormAddress"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model.trim="userchangeForm.address"
            clearable
            maxlength="200"
            placeholder="请输入详细地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <HButton is-modal type="primary" @click="userRegisterAddress">保存</HButton>
        <HButton is-modal @click="checkDialogAddress = false">取消</HButton>
      </template>
    </h-dialog>

    <!-- 修改导入字段-->
    <h-dialog v-model="showEditField" :loading="loadingEditField" title="修改导入字段">
      <el-form
        ref="updateEditFieldFormRef"
        :model="editFieldForm"
        :rules="editFieldFormRules"
        class="modal_form_content"
        inline-message
        label-position="top"
      >
        <el-form-item label="销售部门编号" prop="saleNetworkNumber">
          <el-input
            v-model.trim="editFieldForm.saleNetworkNumber"
            clearable
            placeholder="请输销售部门编号"
          />
        </el-form-item>
        <el-form-item label="销售部门" prop="saleNetworkName">
          <el-input
            v-model.trim="editFieldForm.saleNetworkName"
            clearable
            placeholder="请输销售部门"
          />
        </el-form-item>
        <el-form-item label="出库仓编号" prop="outboundStoreNumber">
          <el-input
            v-model.trim="editFieldForm.outboundStoreNumber"
            clearable
            placeholder="请输出库仓编号"
          />
        </el-form-item>
        <el-form-item label="销货单号" prop="outboundCode">
          <el-input
            v-model.trim="editFieldForm.outboundCode"
            clearable
            placeholder="请输销货单号"
          />
        </el-form-item>
        <el-form-item label="发货单号" prop="sendGoodsNumber">
          <el-input
            v-model.trim="editFieldForm.sendGoodsNumber"
            clearable
            placeholder="请输发货单号"
          />
        </el-form-item>
        <el-form-item label="销售金额" prop="salePrice">
          <el-input
            v-model.trim="editFieldForm.salePrice"
            placeholder="请输销售金额"
            @input="editFieldForm.salePrice = autoFixedDicimal(editFieldForm.salePrice)"
          >
            <template #prepend>￥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="生产日期" prop="">
          <el-date-picker
            v-model="editFieldForm.produceDate"
            :default-value="new Date()"
            style="width: 100%"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        <el-form-item label="出厂日期" prop="">
          <el-date-picker
            v-model="editFieldForm.dateOfProduction"
            :default-value="new Date()"
            style="width: 100%"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>

        <el-form-item label="备注" prop="">
          <el-input
            v-model.trim="editFieldForm.remark"
            clearable
            maxlength="200"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <HButton is-modal type="primary" @click="editFieldSave">保存</HButton>
        <HButton is-modal @click="showEditField = false">取消</HButton>
      </template>
    </h-dialog>

    <!-- 变更记录详情弹窗 -->
    <h-drawer v-model="changeDetail" title="变更历史">
      <change-popup :LOgData="LOgData" :codedetail="detail" />
    </h-drawer>

    <update-user-check-modal
      v-model="updateUserCheckModalVisible"
      :record-id="currentUpdateUserCheckId"
      @update="onUpdateUserCheckModalUpdate"
    />

    <update-warranty-range-apply-modal
      v-model="updateWarrantyDateApplyModalVisible"
      :code-id="detail.id"
      :warranty-start-date="detail.warrantyStartTime"
      :warranty-end-date="detail.warrantyEndTime"
      @update="onUpdateWarrantyRangeApplyModalUpdate"
    />

    <update-warranty-range-date-modal
      v-model="updateWarrantyRangeModalVisible"
      :code-id="detail.id"
      :warranty-start-date="detail.warrantyStartTime"
      :warranty-end-date="detail.warrantyEndTime"
      @update="onUpdateWarrantyRangeApplyModalUpdate"
    />

    <set-backup-machine-modal
      v-model="setBackupMachineModalVisible"
      :code-id="detail.id"
      :standby="detail.standby"
      @update="getDetail(route.params.id as string)"
    />
  </div>
</template>

<script lang="ts" setup>
  import { nextTick, onMounted, reactive, ref, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import type { FormInstance } from 'element-plus'
  import { ElMessageBox } from 'element-plus'
  import ChangePopup from './components/changePopup/index.vue'
  import autoFixedDicimal from '@/utils/money'
  import UpdateUserModal from './components/update-user-modal/index.vue'
  import {
    activCode,
    codeGoodsBindingChange,
    codeGoodsChangeLog,
    deleteCode,
    getCodeFieldInfo,
    getHistoryOrderList,
    loggetList,
    productPageSelect,
    productSpecPageSelect,
    saveCodeFieldInfo,
    saveCodeRegister,
    selecUser,
    sparePageSelect,
    spareSpecPageSelect,
    updateCodeRegisterAddress,
    updateUserRecordDel,
    userChangeList,
  } from '@/api/code'
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import Pagination from '@/components/Pagination/index.vue'
  import _ from 'lodash'
  import { verifyPhone } from '@/utils/validate'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import routeComponentName from '@/config/route-component-name'
  import MountTable from './components/mountTable/index.vue'
  import UpdateUserCheckModal from './components/check-update-user-modal/index.vue'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import UpdateWarrantyRangeApplyModal from './components/warranty-date-range/applyModal.vue'
  import UpdateWarrantyDateRangeApplyLogList from './components/warranty-date-range/applyLogList.vue'
  import { useUserStore } from '@/store/modules/user'
  import UpdateWarrantyRangeDateModal from './components/warranty-date-range/UpdateModal.vue'
  import SetBackupMachineModal from './components/set-backup-machine-modal/index.vue'
  import { useGetSnCodeDetailService } from '@/services/module/code/useCode'
  import { useOrderStore } from '@/store/modules/order'
  import WorkDrawingList from './components/work-drawings/List.vue'

  const { setSnCodeInfo } = useOrderStore()
  const { detail, getDetailLoading, getDetail } = useGetSnCodeDetailService()

  defineOptions({
    name: routeComponentName.snCode.snCodeDetail,
  })

  // 设置设备属性弹窗显示状态
  const setBackupMachineModalVisible = ref(false)

  // 客户状态管理
  const userStore = useUserStore()

  // 变更质保周期申请弹窗显示状态
  const updateWarrantyDateApplyModalVisible = ref(false)

  // 更新质保周期弹窗显示状态
  const updateWarrantyRangeModalVisible = ref(false)

  // 申请更改质保周期记录列表组件实例
  const updateWarrantyDateRangeApplyLogListInstance = ref<InstanceType<
    typeof UpdateWarrantyDateRangeApplyLogList
  > | null>(null)

  const updateRegisterAddressFormRef = ref<FormInstance | null>(null)
  const updateRegisterAddressFormRules: any = ref({
    address: [{ required: true, message: '请填写详细地址', trigger: ['change', 'blur'] }],
    province: [
      { required: true, message: '请选择地址', trigger: ['change', 'blur'] },
      {
        validator: (rule, value, callback) => {
          if (!userchangeForm.province) {
            callback(new Error('请选择省'))
            return
          }

          if (!userchangeForm.city) {
            callback(new Error('请选择市'))
            return
          }

          if (!userchangeForm.area) {
            callback(new Error('请选择区'))
            return
          }

          callback()
        },
        trigger: ['change', 'blur'],
      },
    ],
  })

  const updateInfoSaveLoading = ref(false)
  const updateInfoFormRef = ref<FormInstance | null>(null)
  const updateInfoFormRules = ref({
    goodsId: [{ required: true, message: '请选择新的型号', trigger: ['change', 'blur'] }],
    goodsSpecId: [{ required: true, message: '请选择规格', trigger: ['change', 'blur'] }],
  })

  const customerRegisterFormRef = ref<FormInstance | null>(null)
  const customerRegisterFormRules: any = ref({
    userId: [{ required: true, message: '请选择关联公司', trigger: ['change', 'blur'] }],
    name: [{ required: true, message: '请填写姓名', trigger: ['change', 'blur'] }],
    phone: [
      { required: true, message: '请填写手机号码', trigger: ['change', 'blur'] },
      {
        validator: (rule, value, callback) => {
          if (!verifyPhone(userForm.phone)) {
            callback(new Error('手机号码格式不正确'))
            return
          }
          callback()
        },
        trigger: ['change', 'blur'],
      },
    ],
    address: [{ required: true, message: '请填写详细地址', trigger: ['change', 'blur'] }],
    province: [
      { required: true, message: '请选择地址', trigger: ['change', 'blur'] },
      {
        validator: (rule, value, callback) => {
          if (!userForm.province) {
            callback(new Error('请选择省'))
            return
          }

          if (!userForm.city) {
            callback(new Error('请选择市'))
            return
          }

          if (!userForm.area) {
            callback(new Error('请选择区'))
            return
          }

          callback()
        },
        trigger: ['change', 'blur'],
      },
    ],
  })

  const getOperatedLogsParam = ref({
    createEmp: '',
    limit: 0,
    name: '',
    page: 0,
  })

  const operatedLogs = ref(null)
  const operatedLogPaginationRef = ref<InstanceType<typeof Pagination> | null>(null)

  // 更改客户审核弹窗显示状态
  const updateUserCheckModalVisible = ref(false)

  // 当前正在审核的记录id
  const currentUpdateUserCheckId = ref('')

  /**
   * 申请变更质保周期点击事件
   */
  const onApplyUpdateWarrantyRange = async () => {
    activeName.value = 'updateWarrantyDateRangeLog'
    await nextTick()
    const listInstance = updateWarrantyDateRangeApplyLogListInstance.value
    if (listInstance) {
      await listInstance.getList()
      if (listInstance.isHaveWaitCheck()) {
        HMessageBox.warning('请通知管理员审核')
      } else {
        updateWarrantyDateApplyModalVisible.value = true
      }
    }
  }

  /**
   * 申请变更公司/变更公司点击事件
   */
  const onUpdateUserClick = async () => {
    activeName.value = 'second'
    await getChangeCustomerRecord()
    if (userchangeLOgData.value.some((item) => item.applyState === 0)) {
      HMessageBox.error('请联系管理员审核')
    } else {
      updateUserModalVisible.value = true
    }
  }

  /**
   * 获取申请更改质保周期记录列表
   */
  const getUpdateWarrantyDateRangeApplyLogList = async () => {
    await nextTick()
    if (updateWarrantyDateRangeApplyLogListInstance.value) {
      await updateWarrantyDateRangeApplyLogListInstance.value.getList()
    }
  }

  /**
   * 申请更改质保周期弹窗/更改质保周期弹窗更新事件
   */
  const onUpdateWarrantyRangeApplyModalUpdate = () => {
    activeName.value = 'updateWarrantyDateRangeLog'
    getUpdateWarrantyDateRangeApplyLogList()
    getDetail(route.params.id as string)
  }

  /**
   * 更改客户审核点击事件
   * @param {string} id - 记录id
   */
  const handleUpdateUserCheckClick = (id: string) => {
    updateUserCheckModalVisible.value = true
    currentUpdateUserCheckId.value = id
  }

  /**
   * 更改用户审核弹窗更新事件
   */
  const onUpdateUserCheckModalUpdate = async () => {
    activeName.value = 'second'
    await getChangeCustomerRecord()
  }

  /**
   * 更改客户记录删除按钮点击事件
   * @param {string} id - 记录id
   */
  const handleUpdateUserRecordDelClick = (id: string) => {
    ElMessageBox({
      title: '提示',
      message: '确定要删除改记录',
      type: 'error',
      autofocus: false,
      showCancelButton: true,
      async beforeClose(action, instance, done) {
        if (action === 'confirm') {
          instance.cancelButtonLoading = true
          instance.confirmButtonLoading = true
          const res = await updateUserRecordDel(id)
          instance.cancelButtonLoading = false
          instance.confirmButtonLoading = false
          if (res.data.code === 20000) {
            HMessage.success('删除成功')
            activeName.value = 'second'
            getChangeCustomerRecord()
            done()
            return
          }
          HMessageBox.error(res.data.message)
          return
        }
        done()
      },
    })
  }

  const getOperatedLogs = () => {
    getOperatedLogsParam.value.page = operatedLogPaginationRef.value.current
    getOperatedLogsParam.value.limit = operatedLogPaginationRef.value.size
    loggetList(getOperatedLogsParam.value, route.params.id).then((res) => {
      if (res.data.code == 20000) {
        operatedLogs.value = res.data.data.rows
        total.value = Number(res.data.data.total) || 0
      } else {
        HMessageBox.error(res.data.message)
      }
    })
  }

  const onChangeCustomerUpdate = () => {
    getDetail(route.params.id as string)
    activeName.value === 'second' && getChangeCustomerRecord()
    activeName.value === 'fourth' && getOperatedLogs()
  }

  const tagsViewStore = useTagsViewStore()
  const router = useRouter()
  const route = useRoute()
  const value4 = ref('')
  const loading2 = ref(false)
  const loading3 = ref(false)
  const loading4 = ref(false)
  const changeDialog = ref(false)
  const checkDialog = ref(false)
  const activeName = ref('first')
  const changeDetail = ref(false)
  const updateUserModalVisible = ref(false)
  const loading = ref(true)
  const addrsDom = ref<InstanceType<typeof SingleAddress> | null>(null) //登记地址dom
  const addrsDom2 = ref() //变更登记地址dom
  const paginDom = ref()
  const total = ref(0)
  const relevanceUser = ref()
  const dataPage = {
    limit: 0,
    name: '',
    page: 0,
  }
  const checkDialogAddress = ref(false) //变更登记地址
  const LOgData = ref()
  const userchangeLOgData = ref(null)
  const changeLOgData = ref(null) //变更记录数据
  const loadingtabs = ref(false)
  const historyOrder = ref([]) // 历史工单对象
  const dataInfForm = reactive({
    goodsId: null,
    goodsSpecId: null,
    id: null,
    remark: '',
    tableType: route.params.tableType,
    type: null,
  })
  const userForm = reactive({
    address: '',
    area: '',
    city: '',
    id: null,
    name: '',
    phone: '',
    province: '',
    town: '',
    userId: '',
    adds: {
      province: '',
      area: '',
      city: '',
      town: '',
    },
  })
  const userchangeForm = reactive({
    address: '',
    area: '',
    city: '',
    province: '',
    town: '',
    adds: {
      province: '',
      area: '',
      city: '',
      town: '',
    },
  })
  const gochangeDetail = (val) => {
    changeDetail.value = true
    LOgData.value = val
  }
  const changeSel = (val) => {
    userForm.userId = val
  }
  const remoteMethod = _.throttle((val: string) => {
    if (dataPage.name !== val) {
      dataPage.name = val
      loading2.value = true
      selecUser(dataPage).then((res) => {
        relevanceUser.value = res.data.data.rows
        loading2.value = false
      })
    }
  }, 500)

  const remoteMethod2 = _.throttle((val: string) => {
    loading3.value = true
    changeSwitch(val)
  }, 500)

  // 点击关联用户
  const getinformation = (val) => {
    userForm.userId = val.id
    userForm.address = val.address
    userForm.area = val.area
    userForm.city = val.city
    userForm.name = val.name
    userForm.phone = val.phone
    userForm.province = val.province
    userForm.town = val.town
    userForm.adds = null
    userForm.adds = {
      province: val.province,
      area: val.area,
      city: val.city,
      town: val.town,
    }
  }
  // 手动激活
  const activeOpen = () => {
    ElMessageBox.confirm('是否激活该序列号?', '提示', {
      draggable: true,
      cancelButtonText: '否',
      confirmButtonText: '是',
      type: 'warning',
      autofocus: false,
    }).then(() => {
      var data = [
        {
          id: detail.value.id,
          tableType: route.params.tableType,
        },
      ]
      activCode(data).then((res) => {
        if (res.data.code == 20000) {
          HMessage.success(res.data.message)
          getDetail(route.params.id as string)
          if (activeName.value === 'fourth') {
            getOperatedLogs()
          }
        } else {
          HMessageBox.error(res.data.message)
        }
      })
    })
  }
  // 删除序列号
  const deleCo = () => {
    ElMessageBox.confirm('是否删除该序列号?', '提示', {
      draggable: true,
      cancelButtonText: '否',
      confirmButtonText: '是',
      type: 'error',
      autofocus: false,
    }).then(async () => {
      var data = [
        {
          id: detail.value.id,
          tableType: route.params.tableType,
        },
      ]
      const res = await deleteCode(data)
      if (res.data.code == 20000) {
        HMessage.success(res.data.message)
        tagsViewStore.delView(route.path)
        router.push({ path: '/code/list' })
      } else {
        HMessageBox.error(res.data.message)
      }
    })
  }
  // 点击登记用户弹出
  const userRegister = () => {
    if (detail.value.status != 1) {
      userForm.id = detail.value.id
    }
    checkDialog.value = true
    userForm.address = detail.value.address
    userForm.area = detail.value.area
    userForm.city = detail.value.city
    userForm.name = detail.value.username
    userForm.phone = detail.value.phone
    userForm.province = detail.value.province
    userForm.town = detail.value.town
    userForm.adds = {
      province: detail.value.province,
      area: detail.value.area,
      city: detail.value.city,
      town: detail.value.town,
    }

    selecUser(dataPage).then((res) => {
      relevanceUser.value = res.data.data.rows
    })
  }
  /**修改导入字段 *******************************/
  const showEditField = ref(false)
  const updateEditFieldFormRef = ref()
  const editFieldFormRules = ref({
    //   userId: [{ required: true, message: '请选择关联公司', trigger: ['change', 'blur'] }],
    // name: [{ required: true, message: '请填写姓名', trigger: ['change', 'blur'] }]
  })
  const editFieldForm = ref({
    dateOfProduction: '', //出厂日期
    id: '',
    outboundStoreNumber: '', //出库仓编号
    outboundCode: '',
    produceDate: '', //生产日期
    remark: '',
    saleNetworkName: '', //销售部门名称
    saleNetworkNumber: '', //销售部门编号
    salePrice: '', //销售金额
    sendGoodsNumber: '', //	发货单号
  })
  const loadingEditField = ref(false)
  const changeEditField = () => {
    showEditField.value = true
    loadingEditField.value = true
    getCodeFieldInfo(detail.value.id).then((res) => {
      loadingEditField.value = false
      if (res.data.code == 20000) {
        editFieldForm.value = res.data.data.row
      } else {
        HMessageBox.error(res.data.message)
      }
    })
  }
  // 保存修改导入字段
  const editFieldSave = () => {
    if (!updateEditFieldFormRef.value) {
      return
    }
    loadingEditField.value = true
    updateEditFieldFormRef.value.validate().then(() => {
      saveCodeFieldInfo(editFieldForm.value).then((res) => {
        loadingEditField.value = false
        if (res.data.code == 20000) {
          HMessage.success(res.data.message)
          getDetail(route.params.id as string)
          showEditField.value = false
        } else {
          HMessageBox.error(res.data.message)
        }
      })
    })
  }
  /**********************************************end************ */
  // 变更登记地址弹窗
  const changeuserRegister = () => {
    checkDialogAddress.value = true
  }

  // 变更地址更新事件
  const handleChangeUserFormAddress = (address: {
    province: string
    area: string
    city: string
    town: string
  }) => {
    userchangeForm.province = address.province
    userchangeForm.area = address.area
    userchangeForm.city = address.city
    userchangeForm.town = address.town
  }

  // 保存变更登记地址
  const updateRegisterAddressSaveLoading = ref(false)
  const userRegisterAddress = () => {
    if (!updateRegisterAddressFormRef.value) {
      return
    }
    updateRegisterAddressFormRef.value
      .validate()
      .then(() => {
        updateRegisterAddressSaveLoading.value = true
        updateCodeRegisterAddress({ ...userchangeForm }, detail.value.id).then((res) => {
          updateRegisterAddressSaveLoading.value = false
          if (res.data.code == 20000) {
            checkDialogAddress.value = false
            userchangeForm.address = ''
            userchangeForm.province = ''
            userchangeForm.city = ''
            userchangeForm.area = ''
            userchangeForm.town = ''
            HMessage.success(res.data.message)
            getDetail(route.params.id as string)
            if (activeName.value === 'fourth') {
              getOperatedLogs()
            }
          } else {
            HMessageBox.error(res.data.message)
          }
        })
      })
      .catch(() => {
        // 切不可删除该注释，否则会引起报错
      })
  }

  const options = ref()
  const options2 = ref()

  // 地址更新事件
  const handleAddressChange = (address: {
    province: string
    area: string
    city: string
    town: string
  }) => {
    userForm.province = address.province
    userForm.area = address.area
    userForm.city = address.city
    userForm.town = address.town
  }

  // 保存登记用户
  const registerCustomerLoading = ref(false)
  const onsaveCodeRegister = () => {
    if (!customerRegisterFormRef.value) {
      return
    }
    customerRegisterFormRef.value
      .validate()
      .then(() => {
        registerCustomerLoading.value = true
        saveCodeRegister({ ...userForm }, route.params.id).then((res) => {
          registerCustomerLoading.value = false
          if (res.data.code == 20000) {
            checkDialog.value = false
            HMessage.success(res.data.message)
            getDetail(route.params.id as string)
            if (activeName.value === 'fourth') {
              getOperatedLogs()
            }
          } else {
            HMessageBox.error(res.data.message)
          }
        })
      })
      .catch(() => {
        // 切不可删除该注释，否则会引起报错
      })
  }

  // 修改信息弹窗
  const changeInf = () => {
    changeDialog.value = true
    dataInfForm.type = detail.value.type
    dataInfForm.id = detail.value.id
    changeSwitch('')
  }
  // 修改序列号信息弹窗 =>序列号类型选择变换
  const changeSwitch = async (val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (dataInfForm.type == 1) {
      const res = await productPageSelect(data)
      if (res.data.code == 20000) {
        options.value = res.data.data.rows
      }
      loading3.value = false
    } else {
      const res = await sparePageSelect(data)
      if (res.data.code == 20000) {
        options.value = res.data.data.rows
      }
      loading3.value = false
    }
  }
  // 修改信息保存
  const onSvaeInf = () => {
    if (!updateInfoFormRef.value) {
      return
    }
    updateInfoFormRef.value
      .validate()
      .then(() => {
        updateInfoSaveLoading.value = true
        codeGoodsBindingChange(dataInfForm).then((res) => {
          updateInfoSaveLoading.value = false
          if (res.data.code == 20000) {
            changeDialog.value = false
            HMessage.success(res.data.message)
            getDetail(route.params.id as string)
            if (activeName.value == 'fourth') {
              getOperatedLogs()
            }
            dataInfForm.goodsId = null
            dataInfForm.goodsSpecId = null
            dataInfForm.id = null
            dataInfForm.remark = ''
            dataInfForm.tableType = route.params.tableType
            dataInfForm.type = null
          } else {
            HMessageBox.error(res.data.message)
          }
        })
      })
      .catch(() => {
        // 切不可删除该注释，否则会引起报错
      })
  }
  const remoteMethod3 = _.throttle((val: string) => {
    seleSwitch(val)
  }, 500)
  // 修改序列号信息弹窗 =>型号选择变换
  const seleSwitch = async (val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (!dataInfForm.goodsId) {
      return
    }
    if (dataInfForm.type == 1) {
      const res = await productSpecPageSelect(data, dataInfForm.goodsId)
      if (res.data.code == 20000) {
        options2.value = res.data.data.rows
      }
      loading4.value = false
    } else {
      const res = await spareSpecPageSelect(data, dataInfForm.goodsId)
      if (res.data.code == 20000) {
        options2.value = res.data.data.rows
      }
      loading4.value = false
    }
  }

  // 历史工单
  const getHistoryOrderListApi = async () => {
    const page = {
      page: 0,
      limit: 50,
    }
    historyOrder.value = []
    const res = await getHistoryOrderList(route.params.id, page)
    historyOrder.value = res.data.data.rows
  }

  const getChangeCustomerRecord = async (param?: { limit: number; page: number }) => {
    const data = param || {
      limit: 0,
      page: 0,
    }
    // 变更公司记录
    const res = await userChangeList(data, route.params.id)
    if (res.data.code == 20000) {
      userchangeLOgData.value = res.data.data.rows
      total.value = Number(res.data.data.total)
    } else {
      HMessageBox.error(res.data.message)
    }
    loadingtabs.value = false
  }

  // first历史工单 second变更记录 third操作日志
  const activeNameChange = (val) => {
    let data = {
      limit: 0,
      page: 0,
    }
    loadingtabs.value = true
    switch (val) {
      // 历史工单
      case 'first':
        getHistoryOrderListApi()
        loadingtabs.value = false
        break
      case 'second':
        getChangeCustomerRecord()
        break
      case 'third':
        // 产品溯源
        codeGoodsChangeLog(data, route.params.id).then((res) => {
          if (res.data.code == 20000) {
            changeLOgData.value = res.data.data.rows
            total.value = Number(res.data.data.total)
          } else {
            HMessageBox.error(res.data.message)
          }
          loadingtabs.value = false
        })
        break
      case 'fourth':
        getOperatedLogs()
        loadingtabs.value = false
        break
      case 'fifth':
        loadingtabs.value = false
        break
      case 'updateWarrantyDateRangeLog':
        getUpdateWarrantyDateRangeApplyLogList().then(() => {
          loadingtabs.value = false
        })
        break
      default:
        loadingtabs.value = false
        break
    }
  }
  const successMountList = () => {
    loadingtabs.value = false
  }

  /**
   * 创建工单点击事件
   */
  const onCreateOrderClick = () => {
    setSnCodeInfo(detail.value)
    router.push({ path: '/order/new', query: { mode: 'snCode' } })
  }

  // 监听序列号类型
  watch(
    () => dataInfForm.type,
    () => {
      dataInfForm.goodsId = null
      dataInfForm.goodsSpecId = null
    },
  )

  watch(
    () => dataInfForm.goodsId,
    () => {
      dataInfForm.goodsSpecId = null
    },
  )

  onMounted(async () => {
    await getDetail(route.params.id as string)
    await getHistoryOrderListApi()
    // if (Number(route.query.applyState) === 0) {
    //   activeName.value = 'updateWarrantyDateRangeLog'
    //   activeNameChange('updateWarrantyDateRangeLog')
    // }
  })
</script>

<style scoped lang="scss">
  :deep(.el-form-item) {
    margin: 0;
  }

  .code_detail {
    height: calc(100vh - 92px);
    box-sizing: border-box;
    padding: 12px;
    display: flex;
    flex-direction: column;
    row-gap: 12px;

    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px;
      background-color: #fff;
      flex-wrap: wrap;
      gap: 10px;

      .btn_group,
      .status {
        display: flex;
        align-items: center;
        column-gap: 5px;
      }

      .status {
        .title {
          font-size: 14px;
          font-weight: bold;
        }
      }
    }

    .body {
      height: calc(100% - 64px);
      overflow: auto;
      display: flex;
      flex-direction: column;
      row-gap: 12px;

      // &::-webkit-scrollbar {
      //   display: none;
      // }

      .basic_info {
        display: flex;
        flex-direction: column;
        row-gap: 12px;
        box-sizing: border-box;
        padding: 16px;

        .title {
          font-size: 14px;
          font-weight: bold;
          padding-left: 6px;
          border-left: 3px solid #007cff;
        }

        .info_list {
          display: flex;
          flex-wrap: wrap;
          column-gap: 100px;

          // flex-wrap: wrap;
          // justify-content: space-between;
          // padding: 0 16px;

          .info_item_container {
            display: flex;
            flex-direction: column;

            .info_item {
              height: 26px;
              line-height: 26px;
              display: flex;
              align-items: center;
              column-gap: 5px;

              .label {
                text-align: right;
                color: #606266;
              }

              .value {
                white-space: nowrap;
              }
            }
          }
        }
      }

      .table_code_info {
        display: flex;
        column-gap: 12px;
        flex: 1;
        height: 0;

        .coded_message {
          background-color: #fff;
          box-sizing: border-box;
          padding: 7px 12px;
          width: 240px;

          .title {
            display: flex;
            column-gap: 5px;
            align-items: center;
            height: 39px;

            .text {
              font-size: 14px;
              font-weight: bold;
              padding-left: 6px;
              border-left: 3px solid #007cff;
            }
          }

          .line {
            width: 100%;
            height: 1px;
            background-color: #ebeef5;
          }

          .form_list {
            margin-top: 12px;

            .bor_link {
              border-top: 1px solid #e7e3e3;
              margin: 10px 0;
            }

            .security_code {
              height: 32px;

              :deep(.el-form-item__content) {
                align-items: flex-start;

                .security_code_content {
                  line-height: 14px;
                }
              }
            }

            :deep(.el-form-item__label) {
              font-size: 12px;
              color: #606266;
              height: auto;

              .security_code_label {
                line-height: 14px;
                text-align: center;

                div:last-child {
                  color: #b9b9b9;
                }
              }
            }

            :deep(.el-form-item__content) {
              font-size: 12px;
              // color: #999;
            }

            .state {
              display: inline-block;
              height: 32px;
              line-height: 32px;
              font-weight: 400;
              border-radius: 2px;
              font-size: 12px;
              color: #00c0c0;
            }
          }
        }

        .tabs_container {
          width: calc(100% - 252px);
          // max-height: 600px;
          background-color: #fff;
          box-sizing: border-box;
          padding: 7px 12px;
          padding-bottom: 10px;

          .tabs_header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #ebeef5;
            margin-bottom: 12px;

            .operated_log_search {
              display: flex;
              column-gap: 5px;

              :deep(.el-input) {
                width: 120px;
              }
            }
          }

          .tabs_content {
            height: calc(100% - 51px);

            .history_order {
              max-height: 100%;
            }

            .update_customer_log,
            .product_resource {
              height: 100%;
              display: flex;
              flex-direction: column;
              row-gap: 12px;

              .table {
                max-height: calc(100% - 40px);
              }

              .pagination {
                display: flex;
                justify-content: flex-end;
              }
            }

            .work-drawing {
              width: 100%;
              height: 100%;
            }
          }

          :deep(.el-tabs) {
            .el-tabs__header {
              margin: 0;
              padding: 0;
            }
          }

          :deep(.el-loading-spinner) {
            margin: auto;
          }

          .change_alter {
            display: flex;
            justify-content: flex-start;
            align-items: center;

            .img_zhankai {
              width: 14px;
              height: 14px;
              margin-left: 20px;
              cursor: pointer;
            }
          }

          :deep(.el-table) {
            .cell {
              // text-align: center;
              font-size: 12px;
            }
          }

          .span_state {
            display: inline-block;
            height: 24px;
            line-height: 24px;
            font-weight: 400;
            border-radius: 2px;
            font-size: 12px;
            padding: 0 10px;
          }

          .state1 {
            color: #a06eff;
            border-color: #a06eff;
            background-color: #f3ebff;
          }

          .state2 {
            color: #00c0c0;
            border-color: #00c0c0;
            background-color: #ebf6f6;
          }

          .state3 {
            color: #007cff;
            border-color: #007cff;
            background-color: #eaeff8;
          }

          .state4 {
            color: #122954;
            border-color: #122954;
            background-color: #eaecee;
          }
        }
      }
    }
  }

  .app-container {
    padding-bottom: 0;
  }

  :deep(.el-loading-spinner) {
    margin-top: calc(100% - 66%);
  }

  .el-tag.el-tag--success {
    --el-tag-text-color: #00c0c0;
    --el-tag-bg-color: #ebf6f6;
    --el-tag-border-color: #ebf6f6;
    --el-tag-hover-color: #00c0c0;
  }

  .el-tag.el-tag--info {
    --el-tag-border-color: var(--el-color-info-light-9);
  }

  .el-tag {
    --el-tag-border-color: var(--el-color-primary-light-9);
  }

  .el-tag.el-tag--warning {
    --el-tag-border-color: var(--el-color-warning-light-9);
  }

  .basic_info {
    background-color: #fff;
  }

  .app-container-inner {
    .title_bl {
      border-left: #007cff solid 3px;
      padding-left: 5px;
      font-size: 14px;
      margin: 5px 10px 0;
    }

    .basic_information {
      padding: 10px 10px 0;
      margin: 0 8px;

      :deep(.el-form-item__label) {
        color: #000;
        font-size: 12px;
      }

      .ml {
        font-size: 12px;
        color: #999;
      }

      .state {
        display: inline-block;
        height: 24px;
        line-height: 24px;
        font-weight: 400;
        border-radius: 2px;
        font-size: 12px;
        padding: 0 10px;
        color: #00c0c0;
        border-color: #00c0c0;
        background-color: #ebf6f6;
      }
    }
  }

  .el-main {
    --el-main-padding: 0px;
    display: flex;
    flex-direction: column;
    flex: 1;
  }

  :deep(.change-dialog) {
    .cards {
      .card {
        margin-top: 15px;
        display: flex;
        align-items: center;

        .input-w {
          margin-left: 20px;
          width: 350px;
        }

        .first {
          margin-left: 20px;
        }

        .w350 {
          width: 350px;
          margin-left: 20px;
        }
      }
    }

    .btns {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 25px;
      margin-bottom: 10px;
    }
  }

  :deep(.check-dialog) {
    .addr-item {
      width: 100% !important;
    }

    .cards {
      .el-form-item {
        margin-bottom: 12px;
      }
    }

    .btns {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 25px;
      margin-bottom: 10px;
    }
  }

  :deep(.el-drawer__body) {
    padding: 0 20px;
  }

  .dialog-footer {
    .btn_dialog_Cancel {
      width: 60px;

      &:hover {
        border: 1px solid #e5e5e5;
        color: #999;
        background-color: #e5e5e5;
      }
    }
  }

  .footer {
    padding: 10px 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  :deep(.el-pagination__sizes + button.btn-prev[type='button']) {
    margin-left: 20px;
  }

  .btn_save {
    width: 3.2vw;
  }

  .btn_cancel {
    width: 3.2vw;
  }
</style>
